package com.bawei.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.launch

/**
 * @author ZhangRuiPeng
 * @description:
 */
abstract class BaseFragment<V : ViewBinding, VM : BaseViewModel<*,*>> : Fragment() {

    protected val v : V by lazy { createViewBinding() }
    protected val vm : VM by lazy { createViewModel() }
    protected val inflater : LayoutInflater by lazy { LayoutInflater.from(context) }

    abstract fun createViewBinding() : V
    abstract fun createViewModel() : VM

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return v.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        bindRequestState()
        bindUiState()
    }


    //绑定requsetstate状态方法
    fun bindRequestState(){
        lifecycleScope.launch {
            repeatOnLifecycle( state = Lifecycle.State.STARTED){
                vm.realContainer.requestState
                    .collect{
                        if (it.requestState){
                            requsetStateShow()
                        }else if (it.successState){
                            successStateShow()
                        }else if (it.error){
                            errorStateShow()
                        }
                    }
            }


        }

    }


    //UI 数据状态处理方法
    abstract fun bindUiState()

    //request状态处理
    fun requsetStateShow(){
        ToastUtils.showShort("请求开始")
    }
    //success状态处理
    fun successStateShow(){
        ToastUtils.showShort("请求成功")
    }
    //error状态处理
    fun errorStateShow(){
        ToastUtils.showShort("请求失败")
    }


}